package com.interview.javabasic.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        //创建socket，并将socket绑定到6500端口号
        ServerSocket ss = new ServerSocket(65000);
        //死循环，使得socket一直等待并处理客户端发送过来的请求
        while(true){
            //监听65000端口号，知道客户端返回连接信息后才返回
            Socket socket = ss.accept();
            //获取客户端信息后，执行相关的业务逻辑
            OutputStream os = socket.getOutputStream();
            InputStream is = socket.getInputStream();
            int ch = 0;
            byte[] buff = new byte[1024];
            //buff主要用来读取输入的内容，存成byte数组，ch主要用来获取读取数组长度
            ch = is.read(buff);
            //将接收留的byte数组转换成字符串，这里获取的内容是客户端发送或来的字符串参数
            String content = new String(buff,0,ch);
            System.out.println(content);
            //往输出流里写入获得的字符串的长度，回发给客户端
         /*   Scanner scanner = new Scanner(System.in);
            String serverwords = scanner.next();
            os.write(String.valueOf("Server: "+serverwords).getBytes());
            //不要忘记关闭输入输出流以及socket*/
            is.close();
            os.close();
            socket.close();

        }
    }
}
